package net.flowas.jenkins.plugindownload;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MavenCmdDownloader {
    private static final String downloadCmd = "mvn dependency:get -Dartifact=${groupId}:${artifactId}:${version}:hpi";
    private static final String copyCmd = "mvn dependency:copy -DoutputDirectory="+Configs.getOutDir()+" -Dartifact=${groupId}:${artifactId}:${version}:hpi -Dmdep.stripVersion=true";
    private static final String defaultGroup = "org.jenkins-ci.plugins";
	private Map<String,String> groupIds = new HashMap<>();
    private Map<String,Artifact> artifactList = new HashMap<>();
	private Map<String,String> overrideVersion = new HashMap<>();
	private static final String depenceyTemplate = "<dependency>"
			+ "	<groupId>${groupId}</groupId>"
			+ "	<artifactId>${artifactId}</artifactId>"
			+ "	<version>${version}</version>"
			+ "	<type>hpi</type>"
			+ "</dependency>";
    public void executeDownlod(Artifact artifact) throws IOException {
    	//mvn dependency:get -DoutputDirectory=d:/lib -DgroupId=junit -DartifactId=junit -Dversion=4.12 -Dpackaging=jar
    	/*if(overrideVersion.containsKey(artifact.getId())) {
    		artifact.setVersion(overrideVersion.get(artifact.getId()));
    	}*/
    	String cmd = downloadCmd;
    	cmd  = cmd.replace("${groupId}", artifact.getGroup());
    	cmd  = cmd.replace("${artifactId}", artifact.getId());
    	cmd  = cmd.replace("${version}", artifact.getVersion());
    	Process process = Runtime.getRuntime().exec(cmd);
		readResult(process,cmd);
		process.destroyForcibly();
		cmd = copyCmd;
    	cmd  = cmd.replace("${groupId}", artifact.getGroup());
    	cmd  = cmd.replace("${artifactId}", artifact.getId());
    	cmd  = cmd.replace("${version}", artifact.getVersion());
    	process = Runtime.getRuntime().exec(cmd);
		readResult(process,cmd);
		process.destroyForcibly();
		
		/*String dependencyText = depenceyTemplate.replace("${groupId}", artifact.getGroup());
		dependencyText  = dependencyText.replace("${artifactId}", artifact.getId());
		dependencyText  = dependencyText.replace("${version}", artifact.getVersion());
	    System.out.println(dependencyText);*/
    }
    
    public void init() {
		try {
			URI groupIsdUri = Thread.currentThread().getContextClassLoader().getResource("groupIds.txt").toURI();
			List<String> lines = Files.readAllLines(Paths.get(groupIsdUri));
			for (String line : lines) {
				if (line.startsWith("#")) {
					continue;
				} else if (line.contains(":")) {
					String[] pair = line.split(":");
					groupIds.put(pair[0], pair[1]);
				}
			}
			
			URI dependenciesUri = Thread.currentThread().getContextClassLoader().getResource("dependencyVersions.txt").toURI();
			lines = Files.readAllLines(Paths.get(dependenciesUri));
			for (String line : lines) {
				line=line.trim();
				if (line.contains(":")) {
					String[] pair = line.split(":");
					if(pair.length<3) {
						continue;
					}
					Artifact artifact = new Artifact();
					artifact.setGroup(pair[0]);
					artifact.setId(pair[1]);
					artifact.setVersion(pair[3]);
					artifactList.put(artifact.getId(), artifact);
					//groupIds.put(pair[0], pair[1]);
				}
			}
			
			URI versionOverrideUri = Thread.currentThread().getContextClassLoader().getResource("dependencyVersionOverride.txt").toURI();
			lines = Files.readAllLines(Paths.get(versionOverrideUri));
			for (String line : lines) {
				if (line.startsWith("#")) {
					continue;
				} else if (line.contains(":")) {
					String[] pair = line.split(":");
					overrideVersion.put(pair[0], pair[1]);
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
    
    private void readResult(Process process, String cmd) {
    	//取得命令结果的输出流    
        InputStream fis=process.getInputStream();    
        //用一个读输出流类去读    
        InputStreamReader isr=new InputStreamReader(fis);    
        //用缓冲器读行    
        BufferedReader br=new BufferedReader(isr);    
        String line=null;    
        //直到读完为止    
        try {
			while((line=br.readLine())!=null)    
			{    
				//System.out.println(line); 
				if(line.contains("Final Memory")) {
			    	break;
			    }
				if(line.contains("BUILD FAILURE")) {
					System.out.println("cmd execute failed:"+cmd);
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {
				fis.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}    
    }

    public Artifact getArtifact(String pluginName) {		
		return artifactList.get(pluginName);
	}
    
	public String getGroup(String pluginName) {
		String groupId = groupIds.get(pluginName);
		if(groupId == null) {
			groupId = defaultGroup;
		}
		return groupId;
	}
}
